<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas放大预览</title>
    <style>
        canvas {
            border: 1px solid #000;
            margin-top: 20px;
        }
        #preview {
            position: absolute;
            border: 1px solid #000;
            background-color: white;
            display: none;
            pointer-events: none; /* 禁止预览框阻止交互 */
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="800" height="600"></canvas>
    <canvas id="preview" width="200" height="150"></canvas>

    <script>
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        const previewCanvas = document.getElementById('preview');
        const previewCtx = previewCanvas.getContext('2d');
        const previewWidth = 200; // 预览框大小
        const previewHeight = 150; // 预览框大小
        const scaleFactor = 1.5; // 放大倍数
        const image = new Image();
        image.src = 'https://watermarkud.obs.cn-east-3.myhuaweicloud.com/system/portal-example/inpaint-image/4.jpg';

        image.onload = function() {
            ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
        };

        canvas.addEventListener('mousemove', function(e) {
            const rect = canvas.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            showPreview(x, y);
        });

        function showPreview(x, y) {
            const scaledWidth = previewWidth / scaleFactor;
            const scaledHeight = previewHeight / scaleFactor;
            
            // 设置预览框的位置
            const previewX = Math.max(0, Math.min(canvas.width - scaledWidth, x - scaledWidth / 2));
            const previewY = Math.max(0, Math.min(canvas.height - scaledHeight, y - scaledHeight / 2));
            // previewCanvas.style.left = (x + 10) + 'px';
            // previewCanvas.style.top = (y + 10) + 'px';
            previewCanvas.style.display = 'block';

            // 在预览框中绘制放大的图像
            previewCtx.clearRect(0, 0, previewCanvas.width, previewCanvas.height);
            previewCtx.drawImage(canvas, previewX, previewY, scaledWidth, scaledHeight, 0, 0, previewCanvas.width, previewCanvas.height);
        }

        canvas.addEventListener('mouseout', function() {
            previewCanvas.style.display = 'none'; // 移出canvas范围时隐藏预览框
        });
    </script>
</body>
</html>
